package com.hakgc.rent.dao.impl;

import com.hakgc.rent.dao.BaseDao;
import com.hakgc.rent.dao.UserDao;
import com.hakgc.rent.entity.Street;
import com.hakgc.rent.entity.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/11/17
 */
public class UserDaoImpl extends BaseDao implements UserDao {
    @Override
    public User findByName(String name) {
        String sql = "SELECT uid, uName, uPassword, logo FROM sys_user WHERE uName=?";
        List<User> users = getListFromRS(executeQuery(sql, name));
        if (users != null && users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public List<User> findAll(String likeName) {
        String sql = "SELECT uid, uName, uPassword, logo FROM sys_user ";
        if (likeName!=null && !"".equals(likeName.trim())){
            sql += " WHERE uName LIKE ? ";
            return getListFromRS(executeQuery(sql,"%"+likeName+"%"));
        }
        return getListFromRS(executeQuery(sql));
    }

    @Override
    public boolean save(User user) {
        String sql = "INSERT INTO sys_user(uName, uPassword, logo) VALUES(?, ?, ?)";
        return executeUpdate(sql, user.getName(), user.getPassword(), user.getLogoUrl()) > 0;
    }

    @Override
    public boolean update(User user) {
        String sql = "UPDATE sys_user SET uName=?, uPassword=?, logo=? WHERE uid=?";
        return executeUpdate(sql, user.getName(), user.getPassword(), user.getLogoUrl(), user.getId()) > 0;
    }


    /**
     * 从结果集中获取用户集合
     *
     * @param rs 用户集合的结果集
     * @return 街道集合
     */
    private List<User> getListFromRS(ResultSet rs) {
        List<User> users = null;
        try {
            if (rs != null) {
                users = new ArrayList<>();
                while (rs.next()) {
                    User user = new User();
                    user.setId(rs.getInt("uid"));
                    user.setName(rs.getString("uName"));
                    user.setPassword(rs.getString("uPassword"));
                    user.setLogoUrl(rs.getString("logo"));
                    users.add(user);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 注意：解析完结果集之后一定要按照顺序关闭所有数据库对象
            closeAll();
        }
        return users;
    }
}
